package com.wondertek.service.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.util.base.EncryptUtil;
import com.wondertek.service.dto.sys.req.EmailSendReq;
import com.wondertek.service.dto.sys.req.SysEmailConfigAddReq;
import com.wondertek.service.entity.sys.SysEmailConfigPo;
import com.wondertek.service.mapper.sys.SysEmailConfigMapper;
import com.wondertek.service.service.sys.ISysEmailConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wangyu
 */
@Service
@Slf4j
public class SysEmailConfigServiceImpl extends ServiceImpl<SysEmailConfigMapper, SysEmailConfigPo> implements ISysEmailConfigService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void emailConfig(SysEmailConfigAddReq emailConfigAddReq) {
        SysEmailConfigPo sysEmailConfigPo = getEmailConfig();
        try {
            if(!StrUtil.equals(sysEmailConfigPo.getPass(), emailConfigAddReq.getPass())){
                emailConfigAddReq.setPass(EncryptUtil.desEncrypt(emailConfigAddReq.getPass()));
            }
        } catch (Exception e) {
            log.error("邮箱密码加密失败", e);
            throw new AppException("email.pass.encrypt.fail");
        }
        BeanUtil.copyProperties(emailConfigAddReq, sysEmailConfigPo);
        sysEmailConfigPo.setUpdateBy(null);
        sysEmailConfigPo.setUpdateTime(null);
        this.saveOrUpdate(sysEmailConfigPo);
    }

    @Override
    public SysEmailConfigPo getEmailConfig() {
        return this.lambdaQuery().last("limit 1").one();
    }

    /**
     * 发送邮件 发送人和验证码
     *
     * @param tos 发送人
     * @param code 验证码
     */
    public void send(List<String> tos, String code) {
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("email/email.ftl");
        String content = template.render(Dict.create().set("code",code));
        EmailSendReq emailSendReq = EmailSendReq.builder().tos(tos).subject("You have a new SYSTEM message!").content(content).build();
        this.send(emailSendReq);
    }

    @Override
    public void send(EmailSendReq emailSendReq) {
        if (ObjectUtil.isEmpty(emailSendReq)) {
            throw new AppException("email.send.param.not.null");
        }
        if (CollUtil.isEmpty(emailSendReq.getTos())) {
            throw new AppException("email.toUser.not.null");
        }
        if (StrUtil.isBlank(emailSendReq.getSubject())) {
            throw new AppException("email.subject.not.null");
        }
        if (StrUtil.isBlank(emailSendReq.getContent())) {
            throw new AppException("email.content.not.null");
        }
        SysEmailConfigPo sysEmailConfigPo = getEmailConfig();
        if (ObjectUtil.isEmpty(sysEmailConfigPo)) {
            throw new AppException("email.config.not.null");
        }
        // 封装
        MailAccount account = new MailAccount();
        // 设置用户
        String user = sysEmailConfigPo.getFromUser().split("@")[0];
        account.setUser(user);
        account.setHost(sysEmailConfigPo.getHost());
        account.setPort(sysEmailConfigPo.getPort());
        account.setAuth(true);
        try {
            // 对称解密
            account.setPass(EncryptUtil.desDecrypt(sysEmailConfigPo.getPass()));
        } catch (Exception e) {
            log.error("邮箱密码解密失败", e);
            throw new AppException("email.pass.decrypt.fail");
        }
        account.setFrom(sysEmailConfigPo.getUser() + "<" + sysEmailConfigPo.getFromUser() + ">");
        // ssl方式发送
        account.setSslEnable(true);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(true);
        String content = emailSendReq.getContent();
        // 发送
        try {
            int size = emailSendReq.getTos().size();
            Mail.create(account)
                    .setTos(emailSendReq.getTos().toArray(new String[size]))
                    .setTitle(emailSendReq.getSubject())
                    .setContent(content)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            log.error("发送邮件异常", e);
            throw new AppException("email.send.fail");
        }
    }
}
